package nl.jjsoft.airlock.controller
{
	import com.adobe.utils.StringUtil;
	
	import flash.data.SQLMode;
	import flash.filesystem.File;
	import flash.utils.ByteArray;
	
	import mx.controls.Alert;
	
	import nl.jjsoft.airlock.AirLockConstants;
	import nl.jjsoft.airlock.SqlDB;
	import nl.jjsoft.airlock.domain.Model;
	
	public class LoginControllerMock implements ILoginController
	{
		[Inject]
		public var model:Model;
		
		public function LoginControllerMock()
		{
		}
		
		/**
		 * Change the return type of this method to simuate if the database exists or not.
		 */
		public function dbExists():Boolean {
			return true;
		}

		public function createPasswordDB(safeCombination:String):void
		{			
			var key:ByteArray = getEncryptionKey(safeCombination);			
			var db:SqlDB = new SqlDB();
			// TODO By specifiyn null as the file name, we use an in memory database (for testing purposes)
			db.connect(null, null, SQLMode.CREATE);
			
			var query:String = 'CREATE TABLE IF NOT EXISTS [Groups] ('+
				' [id] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT, '+			
				' [name] VARCHAR(30)  NOT NULL'+			
				' )';
			db.execute(query);			
			query = 'CREATE TABLE IF NOT EXISTS [Passwords] (' +
				' [id] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,'+
				' [group_id] INTEGER  NOT NULL,'+
				' [name] VARCHAR(30)  NOT NULL,'+
				' [url] VARCHAR(200)  NULL,'+
				' [notes] TEXT  NULL,'+
				' [user_name] VARCHAR(100)  NOT NULL,'+
				' [user_pass] NVARCHAR(100)  NOT NULL'+
				' )';
			db.execute(query);
			
			db.disconnect();
			model.selectedView = AirLockConstants.VIEW_MAIN;
		}
		
		private function getEncryptionKey(safeCombination:String):ByteArray {
			var sKey:String = StringUtil.trim(safeCombination);
			var len:int = sKey.length;
			if (len < 16) { // make sure the safeCombination is a string of exactly 16 characters
				const additional:String = "keysAdd$&@&|!#$?";				
				sKey = sKey.concat(additional.slice(len));				
			}
			var bKey:ByteArray = new ByteArray();
			bKey.writeUTFBytes(sKey);
			return bKey;	
			// WHEN USING AS3CORELIB EncryptionKeyGenerator
			//var keygen:EncryptionKeyGenerator = new EncryptionKeyGenerator();
			//return  keygen.getEncryptionKey(sKey);			
		}
		
		public function loginToPasswordDB(safeCombination:String):void {
			var key:ByteArray = getEncryptionKey(safeCombination);
			var db:SqlDB = new SqlDB();

			// TODO By specifiyn null as the file name, we use an in memory database (for testing purposes)			
			if (!db.connect(null, null, SQLMode.UPDATE)) {
				model.safeCombination = null;
				Alert.show("Wrong Safe Combination", "Error");
			}
			else {
				db.disconnect();
				model.safeCombination = safeCombination;
				model.selectedView = AirLockConstants.VIEW_MAIN;	
			}
		}
		
		public function isKeySecure(key:String):Boolean {
			return true;
		}
	}
}